﻿using SaaS.Core;
using System;
using System.Collections.Generic;
using System.Text;
using XCore.Helper;

namespace SaaS.Cache.Auths
{
    /// <summary>
    /// 租户后台授权缓存服务
    /// </summary>
    public class AdminAuthCacheService : AuthCacheServiceBase
    {
        private const string ADMIN_TOKEN = "ADMIN_TOKEN_";
        private const string SITE_ADMIN_PERMISSIONS = "SITE_ADMIN_PERMISSION";
        /// <summary>
        /// 获取租户token
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public string GetTenantToken(int userId)
        {
            return MemoryHelper.Get(ADMIN_TOKEN + userId, () =>
            {
                return base.GetToken(ADMIN_TOKEN, userId);
            });
        }
        /// <summary>
        /// 检查用户token
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public bool CheckTenantToken(int userId, string token)
        {
            return this.GetTenantToken(userId) == token;
        }
        /// <summary>
        /// 移除用户token
        /// </summary>
        /// <param name="userId"></param>
        public void RemoveTenantToken(int userId)
        {
            this.RemoveToken(ADMIN_TOKEN, userId);
            MemoryHelper.Remove(ADMIN_TOKEN + userId);
        }
        /// <summary>
        /// 设置用户token
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        public void SetTenantToken(int userId, string token)
        {
            base.SetToken(ADMIN_TOKEN, userId, token);
            MemoryHelper.Set(ADMIN_TOKEN + userId, TimeSpan.FromHours(CoreSetting.Expire), token);
        }
        public bool IsPermission(int roleId, string permission)
        {
            return base.IsPermission(SITE_ADMIN_PERMISSIONS, roleId, permission);
        }
        public void SavePermission(int roleId, string[] permissions)
        {
            base.SetPermission(SITE_ADMIN_PERMISSIONS, roleId, permissions);
        }
    }
}
